import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';
import 'package:intl/intl.dart';
import 'package:seedfour/app/constants.dart';
import 'package:seedfour/app/models/user_account_entity.dart';
import 'package:seedfour/app/theme.dart';

import 'logic.dart';

class BalancePage extends StatelessWidget {
  BalancePage({Key? key}) : super(key: key);

  final logic = Get.find<BalanceLogic>();
  final state = Get.find<BalanceLogic>().state;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      resizeToAvoidBottomInset: false,
      appBar: AppBar(
        title: const Text('余额'),
        leading: IconButton(
          icon: Icon(
            Icons.arrow_back_ios,
            size: 16.w,
          ),
          onPressed: () {
            Get.back();
          },
        ),
      ),
      body: _buildBg(children: [
        /// 余额部分
        _buildBalanceBg(children: [
          Text(
            '总额(元)',
            style: TextStyle(
              fontSize: kFontSizeMini,
              color: AppColor.colorFontBlack,
            ),
          ),
          SizedBox(height: kSpaceSmall),
          Obx(
            () => Text(
              state.balance.value.replaceAll('¥', ''),
              style: TextStyle(
                fontSize: 44.sp,
                fontWeight: AppFont.fontSemiBold,
              ),
            ),
          ),
          SizedBox(height: kSpaceLarge),
          logic.role == 'me' ? _buildButtons() : Container(),
        ]),

        /// 余额列表
        _buildListBg(children: [
          Container(
            color: Colors.white,
            child: TabBar(
              controller: logic.tabController,
              tabs: state.tabTitles.map((e) => Tab(text: e)).toList(),
            ),
          ),

          /// 分割线
          const Divider(),

          logic.role == 'me'
              ? _buildListItemBg(builder: _balanceItemBuilder)
              : _buildUserListItemBg(builder: _userItemBuilder),
        ]),

        _buildMoreTip(),

        SizedBox(height: kSpaceMedium),
      ]),
    );
  }

  Widget _buildButtons() {
    return Row(
      mainAxisAlignment: MainAxisAlignment.spaceAround,
      children: [
        Expanded(
          child: FilledButton(
            style: FilledButton.styleFrom(
              backgroundColor: AppColor.colorBtnGrey,
              padding: EdgeInsets.symmetric(vertical: 14.w),
              shape: RoundedRectangleBorder(
                borderRadius: BorderRadius.circular(kRadiusMedium),
              ),
            ),
            onPressed: () => logic.onClickWithdraw(),
            child: Text(
              '提现',
              style: TextStyle(
                fontSize: kFontSizeMedium,
                color: AppColor.colorFontBlack,
              ),
            ),
          ),
        ),
        SizedBox(width: kSpaceMedium),
        Expanded(
          child: FilledButton(
            style: FilledButton.styleFrom(
              backgroundColor: AppColor.colorFontBlue,
              padding: EdgeInsets.symmetric(vertical: 14.w),
              shape: RoundedRectangleBorder(
                borderRadius: BorderRadius.circular(kRadiusMedium),
              ),
            ),
            onPressed: () {
              if (!logic.commonService.isAssistant()) {
                logic.onClickTransfer();
              }
            },
            child: Text(
              '转账',
              style: TextStyle(
                fontSize: kFontSizeMedium,
                color: Colors.white,
              ),
            ),
          ),
        ),
      ],
    );
  }

  Widget _buildBalanceBg({required List<Widget> children}) {
    return Container(
      margin: EdgeInsets.all(kSpaceSmall),
      padding:
          EdgeInsets.symmetric(horizontal: kSpaceSmall, vertical: kSpaceMedium),
      decoration: BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.circular(kRadiusMedium),
      ),
      child: Column(
        children: children,
      ),
    );
  }

  Widget _buildListBg({required List<Widget> children}) {
    return Container(
      margin: EdgeInsets.symmetric(horizontal: kSpaceSmall),
      decoration:
          BoxDecoration(borderRadius: BorderRadius.circular(kRadiusMedium)),
      child: Column(
        children: children,
      ),
    );
  }

  Widget _buildUserListItemBg({
    required List<Widget> Function(UserAccountFundData item) builder,
  }) {
    return Obx(
      () => Column(
        children: List.generate(
          state.userList.length,
          (index) => Ink(
            color: Colors.white,
            child: InkWell(
              onTap: () => logic.onClickRecord(index),
              child: Padding(
                padding: EdgeInsets.symmetric(horizontal: kSpaceMedium),
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: builder(state.userList[index]),
                ),
              ),
            ),
          ),
        ),
      ),
    );
  }

  Widget _buildListItemBg({
    required List<Widget> Function(UserAccountBalanceData item) builder,
  }) {
    return Obx(
      () => Column(
        children: List.generate(
          state.balanceList.length,
          (index) => Ink(
            color: Colors.white,
            child: InkWell(
              onTap: () => logic.onClickRecord(index),
              child: Padding(
                padding: EdgeInsets.symmetric(horizontal: kSpaceMedium),
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: builder(state.balanceList[index]),
                ),
              ),
            ),
          ),
        ),
      ),
    );
  }

  List<Widget> _userItemBuilder(UserAccountFundData item) {
    return [
      SizedBox(height: kSpaceSmall),
      Row(
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        children: [
          Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Text(
                item.name,
                style: TextStyle(
                  fontSize: kFontSizeMedium,
                  color: AppColor.colorFontBlack,
                ),
              ),
              SizedBox(height: kSpaceTiny),
              Text(
                item.mobile,
                style: TextStyle(
                  fontSize: kFontSizeMini,
                  color: AppColor.colorFontGrey,
                ),
              ),
            ],
          ),
          SizedBox(width: kSpaceMedium),
          Expanded(
            child: Text(
              textAlign: TextAlign.right,
              '余额：${item.amount}',
              style: TextStyle(
                fontSize: kFontSizeSmall,
                color: AppColor.colorFontBlack,
              ),
            ),
          ),
        ],
      ),
      SizedBox(height: kSpaceSmall),
      const Divider(),
    ];
  }

  List<Widget> _balanceItemBuilder(UserAccountBalanceData item) {
    return [
      SizedBox(height: kSpaceSmall),
      Row(
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        crossAxisAlignment: CrossAxisAlignment.end,
        children: [
          Text(
            item.title ?? '',
            style: TextStyle(
              fontSize: kFontSizeMedium,
              color: AppColor.colorFontBlack,
            ),
          ),
          Text(
            item.changeSubtype == 1
                ? '+${item.amount?.replaceAll('¥', '')}'
                : '-${item.amount?.replaceAll('¥', '')}',
            style: TextStyle(
              fontSize: kFontSizeMedium,
              fontWeight: FontWeight.w500,
            ),
          ),
        ],
      ),
      SizedBox(height: kSpaceMini),
      Row(
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        crossAxisAlignment: CrossAxisAlignment.end,
        children: [
          Text(
            item.createdAt == null
                ? ''
                : DateFormat('yyyy-MM-dd HH:mm').format(
                    DateTime.fromMillisecondsSinceEpoch(item.createdAt!)),
            style: TextStyle(
              fontSize: kFontSizeMini,
              color: Colors.grey,
            ),
          ),
          Text(
            item.afterBalance == null
                ? ''
                : '余额 ${item.afterBalance?.replaceAll('¥', '')}',
            style: TextStyle(
              fontSize: kFontSizeMini,
              color: Colors.grey,
            ),
          ),
        ],
      ),
      SizedBox(height: kSpaceMini),
      Text(
        item.remark ?? '',
        maxLines: 1,
        overflow: TextOverflow.ellipsis,
        style: TextStyle(
          fontSize: kFontSizeMini,
          color: Colors.grey,
        ),
      ),
      SizedBox(height: kSpaceSmall),
      const Divider(),
    ];
  }

  Widget _buildMoreTip() {
    return Center(
      child: Padding(
        padding: EdgeInsets.all(kSpaceMedium),
        child: Obx(
          () => Text(
            state.bottomTips.value,
            style: TextStyle(fontSize: kFontSizeSmall, color: Colors.grey),
          ),
        ),
      ),
    );
  }

  Widget _buildBg({required List<Widget> children}) {
    return Obx(() {
      if (state.isLoading.value) {
        return const Center(child: CircularProgressIndicator());
      } else {
        return RefreshIndicator(
          onRefresh: () async => logic.reload(),
          child: ListView(
            controller: logic.scrollController,
            children: children,
          ),
        );
      }
    });
  }
}
